package com.example.yangyinzhaixian.Fragemt;


import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.yangyinzhaixian.AllActivity.Course2Activity;
import com.example.yangyinzhaixian.AllActivity.RecordActivity;
import com.example.yangyinzhaixian.Bean.Coursejean;
import com.example.yangyinzhaixian.R;
import com.example.yangyinzhaixian.tokendemo.Contants;
import com.example.yangyinzhaixian.tokendemo.Md5Utils;
import com.example.yangyinzhaixian.uitl.OkHttpClientManager;
import com.example.yangyinzhaixian.uitl.SharedPreferencesUtils;
import com.google.gson.Gson;
import com.jude.rollviewpager.RollPagerView;
import com.jude.rollviewpager.adapter.StaticPagerAdapter;
import com.squareup.okhttp.Request;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;

/**
 * A simple {@link Fragment} subclass.
 */
public class CourseFragment extends Fragment {
    private View inflate;
    private ImageView course_btn1;
    private ImageView course_btn2;
    private ImageView course_btn3;
    private ImageView course_btn4;
    private TextView course_text1;
    private TextView course_text2;
    private TextView course_text3;
    private TextView course_text4;
    private ImageView course_btn5;
    private ImageView course_btn6;
    private ImageView course_btn7;
    private ImageView course_btn8;
    private TextView course_text5;
    private TextView course_text6;
    private TextView course_text7;
    private TextView course_text8;
    private ArrayList<TextView> texts;
    private ArrayList<ImageView> image;
    private RollPagerView course_rollpagerview;
    private ImageView prefecture_image1;
    private ImageView prefecture_image2;
    private ImageView prefecture_image3;
    private ImageView prefecture_image4;
    private RecyclerView recommend;
    private RecyclerView master_recycler;
    private MyRollPagerView myRollPagerView;
    private List<Coursejean.DataBean.MasterLivesBean> masterLives;
    private List<Coursejean.DataBean.CourseRecommendsBean> courseRecommends;

    public CourseFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        inflate = inflater.inflate(R.layout.fragment_course, container, false);
        initView(inflate);
        //获取token
        OkHttpUtils.post().url(Contants.BASE_URL+Contants.CREATE_NEW)
                .addParams("device", Build.DEVICE)//设备
                .addParams("deviceKey", getDeviceKey())//设备的key
                .addParams("sdkVersion", String.valueOf(Build.VERSION.SDK_INT))//系统版本
                .addParams("brand", Build.BRAND)//品牌
                .addParams("product", Build.PRODUCT)//产品型号
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.i("TagA", "111" + e.getMessage());
            }

            @Override
            public void onResponse(String response, int id) {
                Log.i("TagA", "222:" + response);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    JSONObject data = jsonObject.getJSONObject("data");
                    String accessToken = data.getString("accessToken");
                    SharedPreferencesUtils.setParam(getActivity(),"Token",accessToken);

//                    OkHttpUtils.get().url("http://api.immedc.com/restapi/live/getLive")
//                            .addHeader("CH-TOKEN", accessToken)
//                            .addParams("liveId", "141")
//                            .build().execute(new StringCallback() {
//                        @Override
//                        public void onError(Call call, Exception e, int id) {
//                            Log.i("TagA", "3333:" + e.getMessage());
//                        }
//
//                        @Override
//                        public void onResponse(String response, int id) {
//                            Log.i("TagA", "44444:" + response);
//
//                        }
//                    });
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
        //获取布局json
        OkHttpClientManager.getAsyn("http://api.immedc.com/restapi/loading/getHome", new OkHttpClientManager.ResultCallback<String>() {
            @Override
            public void onError(Request request, Exception e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(String u) {
                Log.i("USS", "onResponse: " + u);
                Gson gson = new Gson();
                Coursejean coursejean = gson.fromJson(u, Coursejean.class);
                List<Coursejean.DataBean.HomeCategoryBean> homeCategory = coursejean.getData().getHomeCategory();
                //轮播
                List<Coursejean.DataBean.HomeBannerBean> homeBanner = coursejean.getData().getHomeBanner();
                myRollPagerView = new MyRollPagerView(homeBanner);
                course_rollpagerview.setAdapter(myRollPagerView);
                course_rollpagerview.setPlayDelay(2000);
                //菜单
                for (int i = 0; i < image.size(); i++) {
                    texts.get(i).setText(homeCategory.get(i).getTitle());
                    OkHttpClientManager.displayImage(image.get(i), homeCategory.get(i).getBannerUrl());
                }
                List<Coursejean.DataBean.ZlListBean> s = coursejean.getData().getZlList();
                //专栏
                OkHttpClientManager.displayImage(prefecture_image1, s.get(0).getImage());
                OkHttpClientManager.displayImage(prefecture_image2, s.get(1).getImage());
                OkHttpClientManager.displayImage(prefecture_image3, s.get(2).getImage());
                OkHttpClientManager.displayImage(prefecture_image4, s.get(3).getImage());
                //推荐课程
                courseRecommends = coursejean.getData().getCourseRecommends();
                Myrecommend myrecommend = new Myrecommend(courseRecommends);
                recommend.setAdapter(myrecommend);
                myrecommend.setOnlister(new Onlister() {
                    @Override
                    public void setonlister(int position) {
                        Intent intent2 = new Intent(getContext(), Course2Activity.class);
//                        Toast.makeText(getActivity(),courseRecommends.get(position).getCourseId()+"", Toast.LENGTH_SHORT).show();
                        intent2.putExtra("id", courseRecommends.get(position).getCourseId()+"");
                        startActivity(intent2);
                    }
                });
                //大师
                masterLives = coursejean.getData().getMasterLives();
                Mymasterade mymasterade = new Mymasterade(masterLives);
                master_recycler.setAdapter(mymasterade);
                mymasterade.setOnlister(new Onlister() {
                    @Override
                    public void setonlister(int position) {
                        if (masterLives.get(position).getLiveStatus() == 0) {

                        } else {
                            Toast.makeText(getActivity(), "录播", Toast.LENGTH_SHORT).show();
                            Intent intent = new Intent(getContext(), RecordActivity.class);
                            intent.putExtra("LiveId", masterLives.get(position).getLiveId()+"");
                            intent.putExtra("price", masterLives.get(position).getPrice()+"");
                            getActivity().startActivity(intent);
                        }
                    }
                });
            }
        });
        return inflate;
    }

    private void initView(View inflate) {
        course_btn1 = (ImageView) inflate.findViewById(R.id.course_btn1);
        course_btn2 = (ImageView) inflate.findViewById(R.id.course_btn2);
        course_btn3 = (ImageView) inflate.findViewById(R.id.course_btn3);
        course_btn4 = (ImageView) inflate.findViewById(R.id.course_btn4);
        course_text1 = (TextView) inflate.findViewById(R.id.course_text1);
        course_text2 = (TextView) inflate.findViewById(R.id.course_text2);
        course_text3 = (TextView) inflate.findViewById(R.id.course_text3);
        course_text4 = (TextView) inflate.findViewById(R.id.course_text4);
        course_btn5 = (ImageView) inflate.findViewById(R.id.course_btn5);
        course_btn6 = (ImageView) inflate.findViewById(R.id.course_btn6);
        course_btn7 = (ImageView) inflate.findViewById(R.id.course_btn7);
        course_btn8 = (ImageView) inflate.findViewById(R.id.course_btn8);
        course_text5 = (TextView) inflate.findViewById(R.id.course_text5);
        course_text6 = (TextView) inflate.findViewById(R.id.course_text6);
        course_text7 = (TextView) inflate.findViewById(R.id.course_text7);
        course_text8 = (TextView) inflate.findViewById(R.id.course_text8);
        image = new ArrayList<>();
        texts = new ArrayList<>();
        image.add(course_btn1);
        image.add(course_btn2);
        image.add(course_btn3);
        image.add(course_btn4);
        image.add(course_btn5);
        image.add(course_btn6);
        image.add(course_btn7);
        image.add(course_btn8);
        texts.add(course_text1);
        texts.add(course_text2);
        texts.add(course_text3);
        texts.add(course_text4);
        texts.add(course_text5);
        texts.add(course_text6);
        texts.add(course_text7);
        texts.add(course_text8);
        course_rollpagerview = (RollPagerView) inflate.findViewById(R.id.course_rollpagerview);
        prefecture_image1 = (ImageView) inflate.findViewById(R.id.prefecture_image1);
        prefecture_image2 = (ImageView) inflate.findViewById(R.id.prefecture_image2);
        prefecture_image3 = (ImageView) inflate.findViewById(R.id.prefecture_image3);
        prefecture_image4 = (ImageView) inflate.findViewById(R.id.prefecture_image4);
        recommend = (RecyclerView) inflate.findViewById(R.id.recommend);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recommend.setLayoutManager(linearLayoutManager);
        master_recycler = (RecyclerView) inflate.findViewById(R.id.master_recycler);
        LinearLayoutManager linearLayoutManager1 = new LinearLayoutManager(getActivity());
        linearLayoutManager1.setOrientation(LinearLayoutManager.VERTICAL);
        master_recycler.setLayoutManager(linearLayoutManager1);
        master_recycler.setNestedScrollingEnabled(false);
    }

    //轮博适配器
    class MyRollPagerView extends StaticPagerAdapter {
        private List<Coursejean.DataBean.HomeBannerBean> homeBanner;

        public MyRollPagerView(List<Coursejean.DataBean.HomeBannerBean> homeBanner) {
            this.homeBanner = homeBanner;
        }

        @Override
        public View getView(ViewGroup container, int position) {
            ImageView imageView = new ImageView(getActivity());
            imageView.setLayoutParams(new ViewGroup.LayoutParams(GridView.LayoutParams.MATCH_PARENT, GridView.LayoutParams.MATCH_PARENT));
            OkHttpClientManager.displayImage(imageView, homeBanner.get(position).getBannerUrl());
            return imageView;
        }

        @Override
        public int getCount() {
            return homeBanner.size();
        }
    }
    //推荐课程适配器
    class Myrecommend extends RecyclerView.Adapter<Myrecommend.Viewhodler> {
        private List<Coursejean.DataBean.CourseRecommendsBean> courseRecommends;
        private Onlister onlister;

        public void setOnlister(Onlister onlister) {
            this.onlister = onlister;
        }

        public Myrecommend(List<Coursejean.DataBean.CourseRecommendsBean> courseRecommends) {
            this.courseRecommends = courseRecommends;
        }

        class Viewhodler extends RecyclerView.ViewHolder {
            private TextView text;
            private ImageView image;

            public Viewhodler(View itemView) {
                super(itemView);
                image = itemView.findViewById(R.id.recommend_image);
                text = itemView.findViewById(R.id.recommend_text);
                if (onlister!=null)
                {
                    itemView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            onlister.setonlister(getPosition());
                        }
                    });
                }
            }
        }

        @Override
        public Viewhodler onCreateViewHolder(ViewGroup parent, int viewType) {
            View inflate = LayoutInflater.from(getActivity()).inflate(R.layout.recommend, null);
            Viewhodler viewhodler = new Viewhodler(inflate);
            return viewhodler;
        }

        @Override
        public void onBindViewHolder(Viewhodler holder, int position) {
            holder.text.setText(courseRecommends.get(position).getAppTitle());
            OkHttpClientManager.displayImage(holder.image, courseRecommends.get(position).getImageUrl());
        }

        @Override
        public int getItemCount() {
            return courseRecommends.size();
        }
    }
    //大师课适配器
    class Mymasterade extends RecyclerView.Adapter<Mymasterade.Viewhodler> {
        private List<Coursejean.DataBean.MasterLivesBean> masterLives;
        private Onlister onlister;
        public Mymasterade(List<Coursejean.DataBean.MasterLivesBean> masterLives) {
            this.masterLives = masterLives;
        }

        class Viewhodler extends RecyclerView.ViewHolder {
            private TextView text1;
            private TextView text2;
            private TextView text3;
            private TextView text4;
            private TextView text5;
            private ImageView image;

            public Viewhodler(View itemView) {
                super(itemView);
                image = itemView.findViewById(R.id.master_image);
                text1 = itemView.findViewById(R.id.master_text1);
                text2 = itemView.findViewById(R.id.master_text2);
                text3 = itemView.findViewById(R.id.master_text3);
                text4 = itemView.findViewById(R.id.master_text4);
                text5 = itemView.findViewById(R.id.master_text5);
                itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (onlister!=null)
                        {
                            onlister.setonlister(getPosition());
                        }
                    }
                });
            }
        }

        @Override
        public Viewhodler onCreateViewHolder(ViewGroup parent, int viewType) {
            View inflate = LayoutInflater.from(getActivity()).inflate(R.layout.master, null);
            Viewhodler viewhodler = new Viewhodler(inflate);
            return viewhodler;
        }

        @Override
        public void onBindViewHolder(Viewhodler holder, int position) {
            holder.text1.setText(masterLives.get(position).getAppTitle());
            OkHttpClientManager.displayImage(holder.image,masterLives.get(position).getImageUrl());
            if (masterLives.get(position).getLiveStatus() == 0) {
                holder.text5.setText("预告");
            } else {
                holder.text5.setText("录播");
            }
            if (masterLives.get(position).getPrice() == 0) {
                holder.text2.setText("免费");
            } else {
                holder.text2.setText("" + masterLives.get(position).getPrice());
            }
            holder.text3.setText(masterLives.get(position).getTeacherTitle());
            holder.text4.setText("老师:  " + masterLives.get(position).getTeacherName());
        }
        private void setOnlister(Onlister onlister)
        {
            this.onlister=onlister;
        }
        @Override
        public int getItemCount() {
            return masterLives.size();
        }
    }
    private interface Onlister{
        void setonlister(int position);
    }
    //MD5加密
    private String getDeviceKey() {
        String deviceKey = null;
        TelephonyManager tm = (TelephonyManager)getActivity().getSystemService(Context.TELEPHONY_SERVICE);
        deviceKey = tm.getSimSerialNumber();
        deviceKey = Md5Utils.MD5(deviceKey);
        return deviceKey;
    }
    @Override
    public void onStop() {
        super.onStop();
        if (myRollPagerView!=null)
        {
            myRollPagerView.notifyDataSetChanged();
            course_rollpagerview.destroyDrawingCache();
        }
    }
}
